#include "List.h";



LTNode* BuyListNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;

	return newnode;
}

LTNode* LTCreate()
{
	LTNode* phead = BuyListNode(-1);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}

void LTPushBack(LTNode* phead, LTDataType x)
{
	LTNode* newnode = BuyListNode(x);
	LTNode* tail = phead->prev;

	phead->prev->next = newnode;
	newnode->prev = phead->prev;

	phead->prev = newnode;
	newnode->next = phead;
}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	LTNode* tmp = phead->prev->prev;
	tmp->next = phead;
	phead->prev = tmp;
	free(phead->prev);
}

void LTPrint(LTNode* phead)
{
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		
		printf("%d", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

//------------------------------------------------------------


LTNode* LTFind(LTNode* phead, LTDataType x)
{
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}


void LTPushFront(LTNode* phead, LTDataType x)
{
	LTNode* newnode = BuyListNode(x);
	LTNode* next = phead->next;
	
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = next;
	next->prev = newnode;

}


void LTPopFront(LTNode* phead)
{
	LTNode* next = phead->next;
	phead->next = next->next;
	next->next->prev = phead;
	free(phead->next);
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);

	LTNode* newnode = BuyListNode(x);
	LTNode* prev = pos->prev;

	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
	
}

void LTErase(LTNode* pos)
{

	assert(pos);

	LTNode* prev = pos->prev;
	LTNode* next = pos->next;

	prev->next = next;
	next->prev = pos->prev;
	free(pos);
}

void LTDestroy(LTNode* phead)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}

	free(phead);

}